/**
 * 列表转树形
 * @param { Array } list
 * @param { Object } config
 * @return { Array }
 */
export function handleTree(list, config = {}) {
  if (!list || !Array.isArray(list) || !list.length) return list
  let opt = {
    id: 'id', // 主键字段
    parentId: 'parent_id', //父级字段
    children: 'children', // 生成的子级字段
    disabled: 'disabled', // 生成禁用字段
    disabledList: [], // 禁用主键数组
    childEmptyShow: true, // 当子级为空时，是否还保留字段
    disabledShow: true // 当信息为禁用时，是否还保留该信息
  }
  opt = config ? { ...opt, ...config } : opt

  let childes = {}
  let ids = new Set()
  let tree = []
  let arr = []

  for (let i = 0; i < list.length; i++) {
    const el = JSON.parse(JSON.stringify(list[i]))
    if (!(opt.id in el) || !(opt.parentId in el)) continue
    if (opt.disabledList.includes(el[opt.id])) el[opt.disabled] = true
    if (!(el[opt.parentId] in childes)) childes[el[opt.parentId]] = []
    childes[el[opt.parentId]].push(el)
    ids.add(el[opt.id])
    arr.push(el)
  }

  for (let d of arr) {
    if (!ids.has(d[opt.parentId]) && (!d[opt.disabled] || opt.disabledShow)) {
      tree.push(d)
    }
  }

  tree.forEach(t => _getChildList(t))

  function _getChildList(o) {
    if (opt.childEmptyShow) o[opt.children] = []
    if (o[opt.id] in childes) {
      o[opt.children] = childes[o[opt.id]]
    }
    if (o[opt.children] && o[opt.children].length) {
      for (let c of o[opt.children]) {
        _getChildList(c)
      }
    }
  }
  return tree
}

function getTreeParentId(result, list, id, idFiled = 'id', parentFiled = 'parent_id') {
  if (!id && id !== 0) return
  let row = list.find(el => {
    return el[idFiled] + '' === id + ''
  })
  if (row) {
    result.unshift(row)
    getTreeParentId(result, list, row[parentFiled])
  }
}
